package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.Cache;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Cache cache;
    @Override
    public Result get(Long id) {
//        //Shop shop = cache.lock(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        Shop shop = mutexlock(id);
//        if (shop==null){
//            return Result.fail("店铺不存在");
//        }
//        //缓存穿透
//        //Shop shop = shop(id);
//        //互斥锁解决缓存击穿
//        //Shop shop = mutexlock(id);
//        //逻辑法解决缓存击穿
//        //Shop shop = logical(id);
//        return Result.ok(shop);
        //从redis查询
        String shop = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //判断
        if (StrUtil.isNotBlank(shop)) {
            //有返回
            //将json转为java对象
            Shop shop1 = JSONUtil.toBean(shop, Shop.class);
            return Result.ok(shop1);
        }
        if (shop!=null){
            return null;
        }
        //没有查询数据库
        Shop byId = getById(id);
        if (byId==null){
            //存入空
            stringRedisTemplate.opsForValue().set("cache:shop:"+id ,"",2, TimeUnit.MINUTES);
            //没有报错
            return null;
        }
        //数据库有写入redis
        stringRedisTemplate.opsForValue().set("cache:shop:" + id,JSONUtil.toJsonStr(byId));
        return Result.ok(byId);



    }

    //逻辑法
    public Shop logical(Long id){
        //从redis查询
        String shop = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //判断为空返回空
        if (StrUtil.isBlank(shop)) {
            return null;
        }
        //命中，返回Java对象
        RedisData redisData = BeanUtil.toBean(shop, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop1 = BeanUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (!expireTime.isAfter(LocalDateTime.now())){
            //未过期返回商铺信息
            return shop1;
        }
        //过期
        //获取互斥锁
        boolean lock = lock("lock:shop:" + id);
        //判断获取成功
        if (lock) {
            try {
                if (!expireTime.isAfter(LocalDateTime.now())){
                    //未过期返回商铺信息
                    return shop1;
                }
                //开启线程
                pool.submit(()->{
                    //重建缓存
                    addredis(id,30L);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                relax("lock:shop:" + id);
            }
        }

        //返回信息
        return shop1;
    }
    //线程池
    private static final ExecutorService pool= Executors.newFixedThreadPool(10);

    //获取互斥锁方法
    public Shop mutexlock(Long id){
        Shop byId = null;
        try {
            String shop = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
            //判断
            if (StrUtil.isNotBlank(shop)) {
                //有返回
                //将json转为java对象
                Shop shop1 = JSONUtil.toBean(shop, Shop.class);
                return shop1;
            }
            if (shop!=null){
                return null;
            }
            //获取锁
            boolean lock = lock("lock:shop:" + id);
            //判断
            if (!lock) {
                //没有，休眠
                Thread.sleep(50);
                //再次尝试获取
                return mutexlock(id);
            }
            //再次检验缓存是否存在
            String s = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
            //判断
            if (StrUtil.isNotBlank(s)) {
                //有返回
                //将json转为java对象
                Shop shop2 = JSONUtil.toBean(shop, Shop.class);
                return shop2;
            }
            //有查询数据库
            byId = getById(id);
            //模拟延时
            //Thread.sleep(200);
            if (byId==null){
                //存入空
                stringRedisTemplate.opsForValue().set("cache:shop:"+id ,"",2, TimeUnit.MINUTES);
                //没有报错
                return null;
            }
            //数据库有写入redis
            stringRedisTemplate.opsForValue().set("cache:shop:" + id,JSONUtil.toJsonStr(byId),30, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            relax("lock:shop:" + id);
        }
        return byId;
    }

    //解决缓存穿透
    public Shop shop(Long id){
        //从redis查询
        String shop = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //判断
        if (StrUtil.isNotBlank(shop)) {
            //有返回
            //将json转为java对象
            Shop shop1 = JSONUtil.toBean(shop, Shop.class);
            return shop1;
        }
        if (shop!=null){
            return null;
        }
        //没有查询数据库
        Shop byId = getById(id);
        if (byId==null){
            //存入空
            stringRedisTemplate.opsForValue().set("cache:shop:"+id ,"",2, TimeUnit.MINUTES);
            //没有报错
            return null;
        }
        //数据库有写入redis
        stringRedisTemplate.opsForValue().set("cache:shop:" + id,JSONUtil.toJsonStr(byId),30, TimeUnit.MINUTES);
        return byId;
    }

    //定义锁,基于setnx原理
    public boolean lock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 50, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }
    //释放锁
    public void relax(String key){
        stringRedisTemplate.delete(key);
    }

    //设置热点key，以及过期时间添加到redis
    public void addredis(Long id, Long time){
        //查询数据库
        Shop shop = getById(id);
        //设置数据
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(time));
        //写入redis
        stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result updateshop(Shop shop) {
        if (shop.getId()==null){
            Result.fail("店铺id不存在");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete("cache:shop:" + shop.getId());
        return Result.ok();
    }
}
